<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文字转PDF</title>
    <!-- 引入html2pdf.js库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.min.js"></script>
</head>
<body>
    <div class="container">
        <h1>文字转PDF工具</h1>
        <textarea id="textInput" rows="10" cols="50" placeholder="在此输入您的文字..."></textarea>
        <br>
        <button onclick="exportToPDF()">导出为PDF</button>
    </div>

    <style>
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        #textInput {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            font-size: 14pt;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
        .pdf-content {
            font-size: 14pt;
            line-height: 1.5;
            font-family: "SimSun", "宋体", serif;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
    </style>

    <script>
        function exportToPDF() {
            // 获取输入的文字内容
            const textContent = document.getElementById('textInput').value;
            
            if (!textContent.trim()) {
                alert('请输入要转换的文字！');
                return;
            }

            // 创建一个临时的div来存放内容
            const element = document.createElement('div');
            element.className = 'pdf-content';
            // 将文本内容中的换行符转换为<br>标签
            element.innerText = textContent;

            // 配置PDF选项
            const opt = {
                margin: [20, 20, 20, 20], // 上右下左边距，单位mm
                filename: '文档.pdf',
                image: { type: 'jpeg', quality: 0.98 }, // 图片质量
                html2canvas: { 
                    scale: 2, // 提高清晰度
                    useCORS: true
                },
                jsPDF: {
                    unit: 'mm',
                    format: 'a4',
                    orientation: 'portrait'
                },
                pagebreak: {
                    mode: ['avoid-all', 'css', 'legacy'], // 避免元素被分页
                    before: '.page-break-before',
                    after: '.page-break-after'
                }
            };

            // 使用html2pdf转换
            html2pdf()
                .set(opt)
                .from(element)
                .save()
                .catch(err => {
                    console.error('PDF生成失败:', err);
                    alert('PDF生成失败，请重试');
                });
        }
    </script>
</body>
</html>